<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>鼠标移入父div显示子div(且移入子div不隐藏，子div为绝对布局)</title>
  <style>
    .parent {
      position: relative;
      width: 200px;
      height: 200px;
      background-color: lightblue;
      text-align: center;
      line-height: 200px;
    }

    .child {
      position: absolute;
      top: 100%;
      left: 0;
      width: 100%;
      background-color: lightgreen;
      text-align: center;
      padding: 10px;
    }


  </style>

</head>
<body>
<div class="parent" id="parent">
  Hover over me
</div></div>

</body>
<script>
  const parent = document.getElementById('parent'); // 获取父元素
  let child = null; // 初始化子元素

  parent.addEventListener('mouseenter', () => {
    console.log('mouseenter')
    child = document.createElement('div'); // 创建子元素
    child.className = 'child'; // 设置子元素的类名
    child.textContent = "I'm the child"; // 设置子元素的文本内容
    parent.appendChild(child); // 将子元素添加到父元素中
  });

  parent.addEventListener('mouseleave', (e) => {
    console.log('mouseleave')
    if (child && !child.contains(e.relatedTarget)) {
      // 如果子元素存在且鼠标离开的目标不是子元素本身
      parent.removeChild(child); // 从父元素中移除子元素
      child = null; // 将子元素设置为 null
    }
  });



</script>
</html>
